package org.example.demo1.servlets.functionPage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.NovelDao;
import org.example.demo1.DAO.UserNovelDao;
import org.example.demo1.Entity.Novel;
import org.example.demo1.Entity.User;
import org.example.demo1.Entity.UserNovel;
import org.example.demo1.utils.MybatisUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/API/Bookshelf/*")
public class BookshelfServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取会话中的用户信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        // 检查用户是否登录
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", "用户未登录");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }

        // 获取请求路径
        String pathInfo = req.getPathInfo();
        
        try {
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserNovelDao userNovelDao = sqlSession.getMapper(UserNovelDao.class);
            
            // 根据路径处理不同的请求
            if (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("/list")) {
                // 获取分组参数
                String groupName = req.getParameter("groupName");
                List<Novel> novels;
                
                if (groupName != null && !groupName.isEmpty()) {
                    // 获取特定分组的小说列表
                    novels = userNovelDao.getUserCollectionsByGroup(user.getUser_id(), groupName);
                } else {
                    // 获取所有收藏的小说列表
                    novels = userNovelDao.getUserCollections(user.getUser_id());
                }
                
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("msg", "获取成功");
                result.put("total", novels.size());
                result.put("rows", novels);
                
                Gson gson = new GsonBuilder().serializeNulls().create();
                out.write(gson.toJson(result));
            } else if (pathInfo.equals("/groups")) {
                // 获取用户的所有分组
                List<String> groups = userNovelDao.getUserGroups(user.getUser_id());
                
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("msg", "获取成功");
                result.put("total", groups.size());
                result.put("rows", groups);
                
                Gson gson = new Gson();
                out.write(gson.toJson(result));
            } else if (pathInfo.startsWith("/check/")) {
                // 检查用户是否已收藏某小说
                String novelIdStr = pathInfo.substring("/check/".length());
                try {
                    Integer novelId = Integer.parseInt(novelIdStr);
                    UserNovel userNovel = userNovelDao.checkCollection(user.getUser_id(), novelId);
                    
                    Map<String, Object> result = new HashMap<>();
                    result.put("code", 200);
                    result.put("msg", "查询成功");
                    result.put("collected", userNovel != null);
                    if (userNovel != null) {
                        result.put("group_name", userNovel.getGroup_name());
                    }
                    
                    Gson gson = new Gson();
                    out.write(gson.toJson(result));
                } catch (NumberFormatException e) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("code", 400);
                    result.put("msg", "无效的小说ID");
                    
                    Gson gson = new Gson();
                    out.write(gson.toJson(result));
                }
            } else if (pathInfo.matches("/\\d+")) {
                // 处理 /API/Bookshelf/id 路径
                String novelIdStr = pathInfo.substring(1);
                try {
                    Integer novelId = Integer.parseInt(novelIdStr);
                    Novel novel = userNovelDao.getNovelInfoById(user.getUser_id(), novelId);
                
                    Map<String, Object> result = new HashMap<>();
                    if (novel != null) {
                        result.put("code", 200);
                        result.put("msg", "查询成功");
                        result.put("data", novel);
                    } else {
                        result.put("code", 404);
                        result.put("msg", "未找到该书籍");
                    }
                
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    out.write(gson.toJson(result));
                } catch (NumberFormatException e) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("code", 400);
                    result.put("msg", "无效的小说ID");
                
                    Gson gson = new Gson();
                    out.write(gson.toJson(result));
                }
            } else {
                // 未知路径
                Map<String, Object> result = new HashMap<>();
                result.put("code", 404);
                result.put("msg", "未知请求路径");
                
                Gson gson = new Gson();
                out.write(gson.toJson(result));
            }
            
            sqlSession.close();
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "服务器错误: " + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取会话中的用户信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        // 检查用户是否登录
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", "用户未登录");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }
        
        // 获取请求参数
        String novelIdStr = req.getParameter("novelId");
        String action = req.getParameter("action");
        String groupName = req.getParameter("groupName");
        
        if (novelIdStr == null || action == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "参数不完整");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }
        
        try {
            Integer novelId = Integer.parseInt(novelIdStr);
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserNovelDao userNovelDao = sqlSession.getMapper(UserNovelDao.class);
            
            Map<String, Object> result = new HashMap<>();
            
            if ("add".equals(action)) {
                // 添加收藏
                UserNovel existing = userNovelDao.checkCollection(user.getUser_id(), novelId);
                if (existing != null) {
                    result.put("code", 400);
                    result.put("msg", "已经收藏过该小说");
                } else {
                    int rows;
                    if (groupName != null && !groupName.isEmpty()) {
                        // 添加到指定分组
                        rows = userNovelDao.addCollectionWithGroup(user.getUser_id(), novelId, groupName);
                    } else {
                        // 添加到默认分组
                        rows = userNovelDao.addCollection(user.getUser_id(), novelId);
                    }
                    
                    if (rows > 0) {
                        result.put("code", 200);
                        result.put("msg", "收藏成功");
                        sqlSession.commit();
                    } else {
                        result.put("code", 500);
                        result.put("msg", "收藏失败");
                    }
                }
            } else if ("remove".equals(action)) {
                // 取消收藏
                int rows = userNovelDao.removeCollection(user.getUser_id(), novelId);
                if (rows > 0) {
                    result.put("code", 200);
                    result.put("msg", "取消收藏成功");
                    sqlSession.commit();
                } else {
                    result.put("code", 400);
                    result.put("msg", "未收藏该小说");
                }
            } else if ("updateGroup".equals(action)) {
                // 更新分组
                UserNovel existing = userNovelDao.checkCollection(user.getUser_id(), novelId);
                if (existing == null) {
                    result.put("code", 400);
                    result.put("msg", "未收藏该小说");
                } else {
                    int rows = userNovelDao.updateCollectionGroup(user.getUser_id(), novelId, groupName);
                    if (rows > 0) {
                        result.put("code", 200);
                        result.put("msg", "更新分组成功");
                        sqlSession.commit();
                    } else {
                        result.put("code", 500);
                        result.put("msg", "更新分组失败");
                    }
                }
            } else {
                result.put("code", 400);
                result.put("msg", "无效的操作");
            }
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            sqlSession.close();
        } catch (NumberFormatException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "无效的小说ID");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "服务器错误: " + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取会话中的用户信息
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        // 检查用户是否登录
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", "用户未登录");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }
        
        // 获取请求参数 - 先尝试从 URL 参数获取
        String novelIdStr = req.getParameter("novelId");
        
        // 如果 URL 参数中没有，尝试从请求体中读取
        if (novelIdStr == null) {
            try {
                // 读取请求体
                StringBuilder sb = new StringBuilder();
                BufferedReader reader = req.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                
                // 解析请求体中的参数
                String body = sb.toString();
                if (body.contains("novelId=")) {
                    novelIdStr = body.split("novelId=")[1].split("&")[0];
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        // 还可以尝试从路径中获取
        if (novelIdStr == null && req.getPathInfo() != null && req.getPathInfo().length() > 1) {
            novelIdStr = req.getPathInfo().substring(1);
        }
        
        if (novelIdStr == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "参数不完整，缺少小说ID");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            return;
        }
        
        try {
            Integer novelId = Integer.parseInt(novelIdStr);
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserNovelDao userNovelDao = sqlSession.getMapper(UserNovelDao.class);
            
            int rows = userNovelDao.removeCollection(user.getUser_id(), novelId);
            Map<String, Object> result = new HashMap<>();
            
            if (rows > 0) {
                result.put("code", 200);
                result.put("msg", "取消收藏成功");
                sqlSession.commit();
            } else {
                result.put("code", 400);
                result.put("msg", "未收藏该小说");
            }
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            sqlSession.close();
        } catch (NumberFormatException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("msg", "无效的小说ID");
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
        } catch (Exception e) {
            // 处理异常
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("msg", "服务器错误: " + e.getMessage());
            
            Gson gson = new Gson();
            out.write(gson.toJson(result));
            
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
    
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}